<template>
  <div class="behavior-monitoring-panel">
    <!-- 统计卡片 -->
    <a-row :gutter="16" style="margin-bottom: 24px">
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="总行为数"
            :value="statistics.totalBehaviors"
            :value-style="{ color: '#3f8600' }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:cluster-outlined" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="执行中"
            :value="statistics.runningBehaviors"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:play-circle-outlined" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="成功率"
            :value="statistics.successRate"
            :precision="2"
            suffix="%"
            :value-style="{ color: '#52c41a' }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:check-circle-outlined" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="失败率"
            :value="statistics.failureRate"
            :precision="2"
            suffix="%"
            :value-style="{ color: '#ff4d4f' }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:close-circle-outlined" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 工具栏 -->
    <div class="toolbar">
      <a-space>
        <a-button type="primary" @click="refreshData">
          <template #icon>
            <IconifyIcon icon="ant-design:reload-outlined" />
          </template>
          刷新
        </a-button>
        <a-button @click="showAlertModal">
          <template #icon>
            <IconifyIcon icon="ant-design:alert-outlined" />
          </template>
          告警配置
        </a-button>
      </a-space>

      <a-space>
        <a-range-picker
          :value="dateRange"
          @change="handleDateRangeChange"
          style="width: 240px"
        />
        <a-select
          :value="filterType"
          placeholder="行为类型"
          style="width: 150px"
          @change="handleFilter"
        >
          <a-select-option value="">全部类型</a-select-option>
          <a-select-option
            v-for="type in behaviorTypes"
            :key="type.value"
            :value="type.value"
          >
            {{ type.label }}
          </a-select-option>
        </a-select>
      </a-space>
    </div>

    <!-- 监控数据表格 -->
    <a-table
      :columns="columns"
      :data-source="monitoringData"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusLabel(record.status) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'type'">
          <a-tag :color="getTypeColor(record.type)">
            {{ getTypeLabel(record.type) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'performance'">
          <a-progress
            :percent="record.performance"
            :status="getPerformanceStatus(record.performance)"
            size="small"
          />
        </template>

        <template v-else-if="column.key === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="showDetailModal(record)">
              详情
            </a-button>
            <a-button
              v-if="record.alerts && record.alerts.length > 0"
              type="link"
              size="small"
              @click="showAlertsModal(record)"
            >
              告警
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 监控详情模态框 -->
    <a-modal
      :open="detailModalVisible"
      title="监控详情"
      width="800px"
      @cancel="closeDetailModal"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="行为ID">{{
          selectedItem?.id
        }}</a-descriptions-item>
        <a-descriptions-item label="行为名称">{{
          selectedItem?.name
        }}</a-descriptions-item>
        <a-descriptions-item label="行为类型">
          <a-tag :color="getTypeColor(selectedItem?.type)">
            {{ getTypeLabel(selectedItem?.type) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="执行状态">
          <a-tag :color="getStatusColor(selectedItem?.status)">
            {{ getStatusLabel(selectedItem?.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="开始时间">{{
          selectedItem?.startTime
        }}</a-descriptions-item>
        <a-descriptions-item label="结束时间">{{
          selectedItem?.endTime || '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="执行时长">{{
          selectedItem?.duration || '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="性能评分"
          >{{ selectedItem?.performance || 0 }}%</a-descriptions-item
        >
      </a-descriptions>

      <a-divider />

      <a-tabs>
        <a-tab-pane key="metrics" tab="性能指标">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-card title="CPU使用率" size="small">
                <a-progress
                  :percent="selectedItem?.metrics?.cpu || 0"
                  :status="getMetricStatus(selectedItem?.metrics?.cpu)"
                />
              </a-card>
            </a-col>
            <a-col :span="12">
              <a-card title="内存使用率" size="small">
                <a-progress
                  :percent="selectedItem?.metrics?.memory || 0"
                  :status="getMetricStatus(selectedItem?.metrics?.memory)"
                />
              </a-card>
            </a-col>
            <a-col :span="12">
              <a-card title="网络IO" size="small">
                <a-progress
                  :percent="selectedItem?.metrics?.network || 0"
                  :status="getMetricStatus(selectedItem?.metrics?.network)"
                />
              </a-card>
            </a-col>
            <a-col :span="12">
              <a-card title="磁盘IO" size="small">
                <a-progress
                  :percent="selectedItem?.metrics?.disk || 0"
                  :status="getMetricStatus(selectedItem?.metrics?.disk)"
                />
              </a-card>
            </a-col>
          </a-row>
        </a-tab-pane>

        <a-tab-pane key="logs" tab="监控日志">
          <a-timeline>
            <a-timeline-item
              v-for="log in selectedItem?.logs || []"
              :key="log.id"
              :color="getLogColor(log.level)"
            >
              <p>{{ log.message }}</p>
              <p style="color: #999; font-size: 12px">{{ log.timestamp }}</p>
            </a-timeline-item>
          </a-timeline>
        </a-tab-pane>

        <a-tab-pane key="trends" tab="趋势分析">
          <div class="trend-chart">
            <a-empty description="趋势图表功能开发中..." />
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-modal>

    <!-- 告警配置模态框 -->
    <a-modal
      :open="alertModalVisible"
      title="告警配置"
      width="600px"
      @cancel="closeAlertModal"
      @ok="saveAlertConfig"
    >
      <a-form :model="alertConfig" layout="vertical">
        <a-form-item label="CPU告警阈值">
          <a-input-number
            v-model:value="alertConfig.cpuThreshold"
            :min="0"
            :max="100"
            addon-after="%"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="内存告警阈值">
          <a-input-number
            v-model:value="alertConfig.memoryThreshold"
            :min="0"
            :max="100"
            addon-after="%"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="执行时间告警阈值">
          <a-input-number
            v-model:value="alertConfig.timeoutThreshold"
            :min="0"
            addon-after="秒"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="失败率告警阈值">
          <a-input-number
            v-model:value="alertConfig.failureRateThreshold"
            :min="0"
            :max="100"
            addon-after="%"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="告警通知">
          <a-checkbox-group v-model:value="alertConfig.notifications">
            <a-checkbox value="email">邮件通知</a-checkbox>
            <a-checkbox value="sms">短信通知</a-checkbox>
            <a-checkbox value="webhook">Webhook通知</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 告警列表模态框 -->
    <a-modal
      :open="alertsModalVisible"
      title="告警列表"
      width="600px"
      @cancel="closeAlertsModal"
      :footer="null"
    >
      <a-list>
        <a-list-item
          v-for="alert in selectedItem?.alerts || []"
          :key="alert.id"
        >
          <a-list-item-meta>
            <template #title>{{ alert.title }}</template>
            <template #description>{{ alert.description }}</template>
          </a-list-item-meta>
          <template #actions>
            <a-tag :color="getAlertLevelColor(alert.level)">
              {{ getAlertLevelLabel(alert.level) }}
            </a-tag>
          </template>
        </a-list-item>
      </a-list>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'alert-config-updated': [config: any];
}>();

// 响应式数据
const loading = ref(false);
const monitoringData = ref<any[]>([]);
const dateRange = ref<any>(null);
const filterType = ref('');
const detailModalVisible = ref(false);
const alertModalVisible = ref(false);
const alertsModalVisible = ref(false);
const selectedItem = ref<any>(null);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 统计数据
const statistics = reactive({
  totalBehaviors: 156,
  runningBehaviors: 12,
  successRate: 94.5,
  failureRate: 5.5,
});

// 告警配置
const alertConfig = reactive({
  cpuThreshold: 80,
  memoryThreshold: 85,
  timeoutThreshold: 300,
  failureRateThreshold: 10,
  notifications: ['email'],
});

// 行为类型选项
const behaviorTypes = computed(() => [
  { value: 'START', label: '启动' },
  { value: 'STOP', label: '停止' },
  { value: 'CONFIGURE', label: '配置' },
  { value: 'BACKUP', label: '备份' },
  { value: 'MONITOR', label: '监控' },
  { value: 'NOTIFY', label: '通知' },
]);

// 表格列定义
const columns = [
  {
    title: '行为名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '行为类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '执行状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
  },
  {
    title: '性能评分',
    dataIndex: 'performance',
    key: 'performance',
    width: 150,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: 180,
    customRender: ({ text }: { text: string }) =>
      new Date(text).toLocaleString(),
  },
  {
    title: '执行时长',
    dataIndex: 'duration',
    key: 'duration',
    width: 120,
    customRender: ({ text }: { text: number }) => (text ? `${text}秒` : '-'),
  },
  {
    title: '告警数量',
    dataIndex: 'alertCount',
    key: 'alertCount',
    width: 100,
    customRender: ({ text }: { text: number }) =>
      text > 0 ? `${text}个` : '-',
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right',
  },
];

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: 'mon-001',
        name: '资源启动',
        type: 'START',
        status: 'SUCCESS',
        performance: 95,
        startTime: new Date(Date.now() - 300000).toISOString(),
        duration: 60,
        alertCount: 0,
        endTime: new Date(Date.now() - 240000).toISOString(),
        metrics: {
          cpu: 25,
          memory: 30,
          network: 15,
          disk: 10,
        },
        logs: [
          {
            id: '1',
            level: 'INFO',
            message: '开始监控资源启动',
            timestamp: '2024-01-01 10:00:00',
          },
          {
            id: '2',
            level: 'INFO',
            message: '资源启动成功，性能良好',
            timestamp: '2024-01-01 10:01:00',
          },
        ],
        alerts: [],
      },
      {
        id: 'mon-002',
        name: '资源配置',
        type: 'CONFIGURE',
        status: 'RUNNING',
        performance: 78,
        startTime: new Date(Date.now() - 60000).toISOString(),
        duration: null,
        alertCount: 2,
        metrics: {
          cpu: 85,
          memory: 90,
          network: 45,
          disk: 20,
        },
        logs: [
          {
            id: '1',
            level: 'WARN',
            message: 'CPU使用率过高',
            timestamp: '2024-01-01 10:05:00',
          },
          {
            id: '2',
            level: 'WARN',
            message: '内存使用率过高',
            timestamp: '2024-01-01 10:05:30',
          },
        ],
        alerts: [
          {
            id: '1',
            title: 'CPU使用率过高',
            description: 'CPU使用率超过80%',
            level: 'WARNING',
          },
          {
            id: '2',
            title: '内存使用率过高',
            description: '内存使用率超过90%',
            level: 'CRITICAL',
          },
        ],
      },
      {
        id: 'mon-003',
        name: '资源备份',
        type: 'BACKUP',
        status: 'FAILED',
        performance: 45,
        startTime: new Date(Date.now() - 900000).toISOString(),
        duration: 300,
        alertCount: 1,
        endTime: new Date(Date.now() - 600000).toISOString(),
        metrics: {
          cpu: 60,
          memory: 70,
          network: 80,
          disk: 95,
        },
        logs: [
          {
            id: '1',
            level: 'ERROR',
            message: '备份过程中磁盘空间不足',
            timestamp: '2024-01-01 09:45:00',
          },
          {
            id: '2',
            level: 'ERROR',
            message: '备份失败',
            timestamp: '2024-01-01 09:50:00',
          },
        ],
        alerts: [
          {
            id: '1',
            title: '磁盘空间不足',
            description: '磁盘使用率超过95%',
            level: 'CRITICAL',
          },
        ],
      },
    ];

    monitoringData.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    message.error('加载监控数据失败');
    console.error('加载监控数据失败:', error);
  } finally {
    loading.value = false;
  }
};

const refreshData = () => {
  loadData();
};

const handleDateRangeChange = (dates: any) => {
  dateRange.value = dates;
  loadData();
};

const handleFilter = () => {
  pagination.current = 1;
  loadData();
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

const showDetailModal = (item: any) => {
  selectedItem.value = item;
  detailModalVisible.value = true;
};

const closeDetailModal = () => {
  detailModalVisible.value = false;
  selectedItem.value = null;
};

const showAlertModal = () => {
  alertModalVisible.value = true;
};

const closeAlertModal = () => {
  alertModalVisible.value = false;
};

const saveAlertConfig = () => {
  message.success('告警配置保存成功');
  emit('alert-config-updated', alertConfig);
  closeAlertModal();
};

const showAlertsModal = (item: any) => {
  selectedItem.value = item;
  alertsModalVisible.value = true;
};

const closeAlertsModal = () => {
  alertsModalVisible.value = false;
  selectedItem.value = null;
};

const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    SUCCESS: '成功',
    RUNNING: '执行中',
    FAILED: '失败',
    PENDING: '等待中',
  };
  return labelMap[status] || status;
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    SUCCESS: 'success',
    RUNNING: 'processing',
    FAILED: 'error',
    PENDING: 'default',
  };
  return colorMap[status] || 'default';
};

const getTypeLabel = (type: string) => {
  const found = behaviorTypes.value.find((t) => t.value === type);
  return found ? found.label : type;foundfound.labelfoundfound.label
};

const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    START: 'green',
    STOP: 'red',
    CONFIGURE: 'blue',
    BACKUP: 'geekblue',
    MONITOR: 'purple',
    NOTIFY: 'orange',
  };
  return colorMap[type] || 'default';
};

const getPerformanceStatus = (performance: number) => {
  if (performance >= 90) return 'success';
  if (performance >= 70) return 'normal';
  return 'exception';
};

const getMetricStatus = (value: number) => {
  if (value >= 90) return 'exception';
  if (value >= 80) return 'normal';
  return 'success';
};

const getLogColor = (level: string) => {
  const colorMap: Record<string, string> = {
    INFO: 'blue',
    WARN: 'orange',
    ERROR: 'red',
    DEBUG: 'default',
  };
  return colorMap[level] || 'default';
};

const getAlertLevelLabel = (level: string) => {
  const labelMap: Record<string, string> = {
    INFO: '信息',
    WARNING: '警告',
    CRITICAL: '严重',
  };
  return labelMap[level] || level;
};

const getAlertLevelColor = (level: string) => {
  const colorMap: Record<string, string> = {
    INFO: 'blue',
    WARNING: 'orange',
    CRITICAL: 'red',
  };
  return colorMap[level] || 'default';
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="less" scoped>
.behavior-monitoring-panel {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
  }

  .trend-chart {
    min-height: 300px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
